import React, { Component } from 'react'
import { connect } from 'react-redux'
import Taro from '@tarojs/taro'
import { View, Text, Button, Picker, Image } from '@tarojs/components'
import {
  AtInput,
  AtTextarea,
  AtImagePicker,
  AtModal,
  AtModalHeader,
  AtModalAction,
  AtModalContent
} from 'taro-ui'

import { SpCell, SpNavBar, SpAddress } from '@/components'
import api from '@/api'
import { isWxWeb, showToast, isAPP } from '@/utils'
import S from '@/spx'
import imgUploader from '@/utils/upload'

import './applicationForm.scss'

@connect(({ colors }) => ({
  colors: colors.current
}))
export default class applicationForm extends Component {
  constructor(props) {
    super(props)
    this.state = {
      info: {},
      chooseValue: [],
      isOpened: false,
      agentRange: [],
      agentRangeIndex: null,
      imgName: '',
      isImgOpened: false
    }
  }
  // 可以使用所有的 React 生命周期方法
  componentDidMount() {}

  // onLoad
  onLoad() {
    this.shopAppl()
    api.distribution.agent().then((res) => {
      this.setState({
        agentRange: res
      })
    })
  }

  // onReady
  onReady() {}

  // 对应 onShow
  componentDidShow() {}

  // 对应 onHide
  componentDidHide() {}

  // 对应 onPullDownRefresh，除了 componentDidShow/componentDidHide 之外，
  // 所有页面生命周期函数名都与小程序相对应
  onPullDownRefresh() {}
  /**
   * 检查是否审核中
   */
  shopAppl = () => {
    api.distribution.shopAppl().then((res) => {
      if (res.status === 3) {
        showToast('审核拒绝,请重新申请.')
        const { agentRange } = this.state

        let index = null
        agentRange.map((item, i) => {
          if (item.agent_id == res.seek_agent_id) {
            index = i
          }
        })
        this.setState({
          chooseValue: [res.province, res.city, res.county],
          info: {
            promoter_name: res.promoter_name,
            telephone: res.telephone,
            adrdetail: res.adrdetail,
            wxgroup_name: res.wxgroup_name,
            group_num: res.group_num,
            wx_group_pic: res.wx_group_pic,
            business_license_pic: res.business_license_pic
          },
          agentRangeIndex: index
        })
      } else if (res.status === 1) {
        showToast('审核中,请等待审核.', Taro.navigateBack)
      }
    })
  }
  /**
   * 省市区显示
   */
  onPickerClick = () => {
    this.setState({ isOpened: true })
  }
  /**
   * 省市区隐藏
   */
  handleClickClose = () => {
    this.setState({ isOpened: false })
  }
  /**
   * 省市区回调
   * @param {Object} selectValue
   */
  onPickerChange = (selectValue) => {
    const chooseValue = [selectValue[0].label, selectValue[1].label, selectValue[2].label]
    this.setState({ chooseValue })
  }
  /**
   * 输入框回调
   * @param {String} name 输入框名称
   * @param {String/Number} val
   * @param {Object} e
   */
  handleChange = (name, val, e) => {
    const nInfo = JSON.parse(JSON.stringify(this.state.info || {}))
    if (name === 'adrdetail') {
      nInfo[name] = e.detail.value
    } else {
      nInfo[name] = val
    }
    this.setState({
      info: nInfo
    })
  }
  authorityShow = (name) => {
    if (isAPP()) {
      //获取检测权限的状态
      var checkResult = plus.navigator.checkPermission('android.permission.READ_EXTERNAL_STORAGE')
      if (checkResult === 'undetermined' || checkResult === 'denied') {
        this.setState({
          imgName: name,
          isImgOpened: true
        })
      } else {
        this.onUploadAvatarFile(name)
      }
    } else {
      this.onUploadAvatarFile(name)
    }
  }
  /**
   * 图片上传
   * @param {String} name 图片类型
   * @param {Object} data 图片对象
   * @param {String} type 操作类型
   * @returns
   */
  onUploadAvatarFile = async (name) => {
    const { info } = this.state
    const { tempFiles = [] } = await Taro.chooseImage({
      count: 1
    })
    if (tempFiles.length > 0) {
      const imgFiles = tempFiles.slice(0, 1).map((item) => {
        return {
          file: item,
          url: item.path
        }
      })
      const res = await imgUploader.uploadImageFn(imgFiles)
      let data = { ...info }
      data[name] = res[0].url
      this.setState({
        info: data
      })
    }
  }
  /**
   * 代理商选择
   */
  agentOnChange = (e) => {
    this.setState({
      agentRangeIndex: e.detail.value
    })
  }
  /**
   * 提交
   */
  handleSubmit = () => {
    const { chooseValue, info, agentRange, agentRangeIndex } = this.state
    const data = info

    if (!data.promoter_name) {
      return showToast('请输入团长姓名')
    }

    if (!data.telephone) {
      return showToast('请输入电话')
    }

    if (!chooseValue.length) {
      return showToast('请选择省市区')
    }
    if (!data.adrdetail) {
      return showToast('请输入详细地址')
    }
    if (!data.wxgroup_name) {
      return showToast('请输入微信群名或群号')
    }
    if (!data.group_num) {
      return showToast('请输入微信群内实际人数')
    }
    if (!agentRangeIndex) {
      return showToast('请输入选择代理商')
    }
    if (!data.wx_group_pic) {
      return showToast('请上传微信群截图')
    }
    if (!data.business_license_pic) {
      return showToast('上传营业执照')
    }

    Taro.showModal({
      title: '申请销售团长',
      content: '是否申请销售团长',
      cancelText: '取消',
      confirmText: '确定'
    }).then((e) => {
      if (e.confirm) {
        data.province = chooseValue[0]
        data.city = chooseValue[1]
        data.county = chooseValue[2]
        data.seek_agent_id = agentRange[agentRangeIndex].agent_id
        Taro.showLoading('正在提交')
        api.distribution
          .shopSave(data)
          .then((res) => {
            Taro.hideLoading()
            if (res.status) {
              showToast('申请成功等待审核', Taro.navigateBack())
            }
          })
          .catch(() => {
            Taro.hideLoading()
          })
      }
    })
  }

  render() {
    const { colors } = this.props
    const { info, chooseValue, isOpened, isImgOpened, agentRange, imgName, agentRangeIndex } =
      this.state
    return (
      <View className='page-address-edit' style={isWxWeb && { paddingTop: 0 }}>
        <SpNavBar title='新增销售团长' leftIconType='chevron-left' fixed='true' />
        <View className='page-address-edit__form'>
          <SpCell
            className='logistics-no border-bottom'
            required
            title='团长姓名'
            value={
              <AtInput
                name='promoter_name'
                value={info.promoter_name}
                placeholder='请输入姓名'
                onChange={(e) => this.handleChange('promoter_name', e)}
              />
            }
          ></SpCell>

          <SpCell
            className='logistics-no border-bottom'
            title='电话'
            required
            value={
              <AtInput
                type='phone'
                name='telephone'
                value={info.telephone}
                placeholder='请输入电话号码'
                onChange={(e) => this.handleChange('telephone', e)}
              />
            }
          ></SpCell>

          <SpCell
            className='logistics-no province border-bottom'
            title='所在省市区'
            required
            isLink
            arrow
            value={
              <View className='picker' onClick={this.onPickerClick}>
                {chooseValue.join('') === '' ? (
                  <Text>选择省/市/区</Text>
                ) : (
                  <Text style={{ color: '#222' }}>{chooseValue.join('/')}</Text>
                )}
              </View>
            }
          ></SpCell>
          <SpAddress
            isOpened={isOpened}
            onClose={this.handleClickClose}
            onChange={this.onPickerChange}
          />

          <SpCell required className='logistics-no detail-address' title='详细地址'>
            <AtTextarea
              count={false}
              name='adrdetail'
              value={info.adrdetail}
              maxLength={100}
              placeholder='请填写详细地址（街道、门牌）'
              onChange={this.handleChange.bind(this, 'adrdetail')}
            />
          </SpCell>
          <SpCell
            required
            className='logistics-no border-bottom'
            title='微信群名称'
            value={
              <AtInput
                name='wxgroup_name'
                value={info.wxgroup_name}
                placeholder='微信群名或群号'
                onChange={(e) => this.handleChange('wxgroup_name', e)}
              />
            }
          ></SpCell>
          <SpCell
            required
            className='logistics-no border-bottom'
            title='群内人数'
            value={
              <AtInput
                name='group_num'
                type='number'
                value={info.group_num}
                placeholder='微信群内实际人数'
                onChange={(e) => this.handleChange('group_num', e)}
              />
            }
          ></SpCell>
          <SpCell
            required
            className='logistics-no border-bottom'
            title='代理商'
            value={
              <Picker
                mode='selector'
                range={agentRange}
                rangeKey='agents_name'
                onChange={this.agentOnChange}
              >
                {agentRangeIndex ? (
                  <View className='agentText'>{agentRange[agentRangeIndex].agents_name}</View>
                ) : (
                  <View className='defaultText'>请选择代理商</View>
                )}
              </Picker>
            }
          ></SpCell>
          <SpCell required className='imagePickerCell' title='上传微信群截图'>
            <View
              className='imagePicker'
              onClick={() => {
                this.authorityShow('wx_group_pic')
              }}
            >
              {info.wx_group_pic ? (
                <Image src={info.wx_group_pic} mode='aspectFill' className='image' />
              ) : (
                <View className='imagePicker__choose-btn'>
                  <View className='add-bar'></View>
                  <View className='add-bar'></View>
                </View>
              )}
            </View>
          </SpCell>
          <SpCell required className='imagePickerCell' title='上传营业执照'>
            <View
              className='imagePicker'
              onClick={() => {
                this.authorityShow('business_license_pic')
              }}
            >
              {info.business_license_pic ? (
                <Image src={info.business_license_pic} mode='aspectFill' className='image' />
              ) : (
                <View className='imagePicker__choose-btn'>
                  <View className='add-bar'></View>
                  <View className='add-bar'></View>
                </View>
              )}
            </View>
          </SpCell>
        </View>
        <View className='btns'>
          <Button
            type='primary'
            onClick={this.handleSubmit}
            className='submit-btn'
            style={`background: ${colors.data[0].primary}; border-color: ${colors.data[0].primary};border-radius: 25px;`}
          >
            确定
          </Button>
        </View>
        <AtModal isOpened={isImgOpened}>
          <AtModalHeader>申请储存与摄像头权限</AtModalHeader>
          <AtModalContent>
            应用的图片上传功能需要获取读写手机存储与摄像头权限，请允许。
          </AtModalContent>
          <AtModalAction>
            <Button
              onClick={() => {
                this.setState({ isImgOpened: false })
              }}
            >
              关闭
            </Button>
            <Button
              style='color: #21B991;margin-top:0;'
              onClick={() => {
                plus.android.requestPermissions(
                  [
                    'android.permission.READ_EXTERNAL_STORAGE',
                    'android.permission.WRITE_EXTERNAL_STORAGE',
                    'android.permission.CAMERA'
                  ],
                  () => {
                    this.onUploadAvatarFile(imgName)
                  }
                )
                this.setState({ isImgOpened: false })
              }}
            >
              下一步
            </Button>
          </AtModalAction>
        </AtModal>
      </View>
    )
  }
}
